package com.peanut.baby.mvp.web.x5;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;

import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.util.ShareUtil;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by anonymouslystudio on 2017/8/9.
 */

public class X5WebViewActivity extends BaseMvpActivity implements TitleLayout.OnTitleClickListener{
    private static final String TAG = X5WebViewActivity.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.webview_progress)
    ProgressBar progressBar;

    private String url, titleStr,imgUrl;

    public static void start(Context ctx, String url, String title,String imgUrl) {
        ctx.startActivity(new Intent(ctx, X5WebViewActivity.class).putExtra("url", url).putExtra("title", title).putExtra("imgUrl", imgUrl));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("X5","X5 onCreate");
        setContentView(R.layout.activity_web_x5);
        ButterKnife.bind(this);
        url = getIntent().getStringExtra("url");
        titleStr = getIntent().getStringExtra("title");
        imgUrl = getIntent().getStringExtra("imgUrl");
        initView();

    }

    /**
     *
     */
    private void initView() {
        title.setOnTitleClickedListener(this);
        title.setTitle(StringUtil.isNullOrEmpty(titleStr)? "详情":titleStr);
        title.setTitleBackVisibility(true);
        title.setTitleRightTextDrawable("", R.drawable.icon_share);
        title.setTitleRightVisibility(true);

        if(url.equals(HttpConfig.WIKI_URL)){
            title.setTitleRightTextDrawable("", R.drawable.icon_share);
            title.setTitleRightVisibility(true);
        }

        com.tencent.smtt.sdk.WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(false);
        settings.setUseWideViewPort(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //
        settings.setDomStorageEnabled(true);


        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setWebViewClient(new MyWebClient());
        webView.setDownloadListener(new MyDownloadListener());

        webView.loadUrl(url);
    }

    @Override
    public void onTitleBackClicked() {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            finish();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(webView.canGoBack()){
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onTitleRightClicked() {
        String currentUrl = webView.getUrl();
        String currentTitle = webView.getTitle();
        String shareTitle = currentUrl.contains("weidian")?"花生好孕优选-备孕怀孕调理营养滋补良品":currentTitle;

        String fixedTitle = getShareTitle(currentUrl,shareTitle);
        String fixedDesc = getShareDesc(currentUrl,currentTitle);

        Log.d(TAG,"fixedtitle "+fixedTitle+"\nfixedDesc "+fixedDesc);


        new BaseDialog().showShareDialog(X5WebViewActivity.this, new BaseDialog.OnShareItemSelected() {
            @Override
            public void onShareItemSelected(int item) {
                String platName = "";
                if(item == BaseDialog.OnShareItemSelected.TYPE_MOMENT){
                    platName = WechatMoments.NAME;
                }else if(item == BaseDialog.OnShareItemSelected.TYPE_WEIXIN){
                    platName = Wechat.NAME;
                }else if(item == BaseDialog.OnShareItemSelected.TYPE_WEIBO){
                    platName = SinaWeibo.NAME;
                }else if(item == BaseDialog.OnShareItemSelected.TYPE_QQ){
                    platName = QQ.NAME;
                }
                if(StringUtil.isNullOrEmpty(platName)){
                    return;
                }
                ShareUtil.getInstance().share(fixedTitle,fixedDesc,currentUrl,platName,imgUrl, new ShareUtil.IShareCallback() {
                    @Override
                    public void onShareFinished(boolean isSuccess, String platformName, String failReason) {
                        showToast(isSuccess?"分享成功":failReason);

                    }
                });
            }
        });
    }

    @Override
    public void onTitleClicked() {

    }

    /**
     * webVIew设置进度条
     */
    class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressBar.setProgress(newProgress);
        }

    }

    class MyWebClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);


        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            Log.d(TAG,"onReceivedError->"+error.toString());
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            Log.d(TAG,"onReceivedError->"+errorResponse.toString());
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            sslErrorHandler.proceed();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            try {
                if (!TextUtils.isEmpty(url)) {
                    // 处理自定义scheme协议
                    if (!url.startsWith("http") && !url.startsWith("https")) {
                        try {
                            final Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            intent.addCategory("android.intent.category.BROWSABLE");
                            intent.setComponent(null);
                            if (null != intent) {
                                startActivity(intent);
                            }
                            return true;
                        } catch (Exception e) {
                            // 没有安装的情况
                            e.printStackTrace();
                            return super.shouldOverrideUrlLoading(view,url);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (url.startsWith("http") || url.startsWith("https")) {
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

    }

    private String getShareTitle(String url,String orgTitle){
        if(url.contains("from=999999")){
            //首页
            return "花生好孕优选-备孕怀孕调理营养滋补良品";
        }else if(isSecondWeidianCat(url)){
            //微店目录
            return "花生好孕优选-备孕怀孕调理营养滋补良品";
        }else{
            return orgTitle;
        }

    }
    private String getShareDesc(String url,String orgDesc){
        if(url.contains("from=999999")){
            //首页
            return "10秒成为合伙人，开启省钱、赚钱和赚钱模式。";
        }else if(isSecondWeidianCat(url)){
            //微店目录
            String cat = getCatByUrl(url);
            return "【"+cat+"】";
        }else{
            return orgDesc;
        }
    }

    String getCatByUrl(String url){
        HashMap<String, String> map = getWeidianCatMap();
        String cat = "";
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()){
            String key = iter.next();
            if(url.contains(key)){
                cat = map.get(key);
                break;
            }
        }

        return cat;
    }

    private boolean isSecondWeidianCat(String url){
        HashMap<String, String> map = getWeidianCatMap();
        boolean isCat = false;
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()){
            String key = iter.next();
            if(url.contains(key)){
                isCat = true;
                break;
            }
        }

        return isCat;
    }


    private HashMap<String, String> getWeidianCatMap(){
        HashMap<String,String> map = new HashMap<>();
        map.put("125133145","女士滋补");
        map.put("125133150","男士滋补");
        map.put("122315686","新鲜美味");
        map.put("125318590","药食同源");
        map.put("134350640","好孕良品");
        map.put("117512834","备孕调理");

        map.put("134684709","女士综合调养");
        map.put("134684710","男士综合调养");
        map.put("134684737","营养均衡");
        map.put("134684741","滋补调养");
        map.put("134684617","月经调养");

        map.put("134684618","子宫调养");
        map.put("134684660","卵巢调养");
        map.put("134684626","补气养血");
        map.put("134684656","健脾养胃");
        map.put("134684800","通经活络");
        map.put("134684622","驱寒祛湿");

        map.put("134684620","祛火消炎");
        map.put("134684747","促排养卵");
        map.put("134684624","减肥养颜");
        map.put("134684706","补肾养精");
        map.put("134684708","正阳固本");

        return map;
    }


    class MyDownloadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String arg0, String arg1, String arg2,
                                    String arg3, long arg4) {
            Uri uri = Uri.parse(arg0);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }
}
